package com.heima.behavlor.service.impl;

import com.heima.behavlor.service.ApArticleBehaviorService;
import com.heima.behavlor.service.ApBehaviorEntryService;
import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.ArticleBehaviorDTO;
import com.heima.model.behavior.pojos.*;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.wemedia.pojos.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @package com.heima.behavlor.service.impl
 * @Date 2022/3/8
 * @project heima-leadnews
 */
@Service
public class ApArticleBehaviorServiceImpl implements ApArticleBehaviorService {
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    StringRedisTemplate redisTemplate;
    /**
     * 文章关系
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDTO dto) {
        ArticleAll articleAll = new ArticleAll();
        //判断登录
        ApUser user = AppThreadLocalUtils.getUser();
        new ArticleBehaviorDTO();
        if (user==null){
            //未登录,全返回false
           return ResponseResult.okResult(articleAll);
        }
        ApBehaviorEntry entry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), null);
        Query query = Query.query(Criteria.where("entryId").is(entry.getId()).and("articleId").is(dto.getArticleId()));
        if (mongoTemplate.findOne(query, ApLikesBehavior.class)!=null) {
            articleAll.setIslike(true);
        }
        if (mongoTemplate.findOne(query, ApUnlikesBehavior.class)!=null) {
            articleAll.setIsunlike(true);
        }
        if (mongoTemplate.findOne(query, ApCollection.class)!=null) {
            articleAll.setIscollection(true);
        }
        Double score = redisTemplate.opsForZSet().score(UserRelationConstants.FOLLOW_LIST+user.getId(),String.valueOf(dto.getAuthorApUserId()));
        if (score!=null){
            articleAll.setIsfollow(true);
        }

        return ResponseResult.okResult(articleAll);
    }
}
